<?php

namespace App\Models;

class Semver {
    public $majer = 0;
    public $minor = 0;
    public $patch = 0;
    public $extra = null;

    public function __construct($majer = 0,$minor = 0,$patch = 0,$extra = null) {
        $this->majer = $majer;
        $this->minor = $minor;
        $this->patch = $patch;
        $this->extra = $extra;
    }

    public static function parse($ver,$extra = NULL) {
        $t = explode('.',$ver);
        $majer = isset($t[0]) ? intval($t[0]) : 0;
        $minor = isset($t[1]) ? intval($t[1]) : 0;
        $patch = isset($t[2]) ? intval($t[2]) : 0;
        return new Semver($majer,$minor,$patch,$extra);
    }

    public function cmp(Semver $that) {

        if ($this->majer != $that->majer)
        {
            return $this->majer > $that->majer ? 100 : -1;
        }

        if ($this->minor != $that->minor)
        {
            return $this->minor > $that->minor ? 10 : -1;
        }

        if ($this->patch != $that->patch) {
            return $this->patch > $that->patch ? 1 : -1;
        }

        return 0;
    }

    public static function latest($thats)
    {
        $latest = $thats[0];
        foreach($thats as $that) {
            if ($latest->cmp($that) < 0) {
                $latest = $that;
            }
        }

        return $latest;
    }

    public function __toString() {
        return $this->majer . '.' . $this->minor . '.' . $this->patch;
    }
}
